#include "udpbase.h"

UdpBase::UdpBase(QObject *parent) : QObject(parent)
{

}

void UdpBase::setConfig(ENCODE_PARAM m_cfg)
{
    m_srcIP = m_cfg._srcIp;
    m_srcPort = m_cfg._srcPort;

    m_bindIP = m_cfg._bindIp;
    m_bindPort = m_cfg._bindPort;
}


int UdpBase::getNetCardIndex(QString interfaceName)
{
    QList<QNetworkInterface> list = QNetworkInterface::allInterfaces();
    foreach(const QNetworkInterface &intf, list){
        if(intf.name().contains(interfaceName) == true){
            return intf.index();
        }
    }
    return -1;
}

QNetworkInterface UdpBase::getNetInterface(QString ip)
{
    QNetworkInterface targetInterface;

    // 枚举所有可用网卡，筛选出支持组播且活跃的网卡
    QList<QNetworkInterface> interfaces = QNetworkInterface::allInterfaces();
    foreach (const QNetworkInterface& iface, interfaces) {
        // 检查网卡是否活跃且支持组播
        if (!(iface.flags() & QNetworkInterface::IsUp) ||
            !(iface.flags() & QNetworkInterface::IsRunning) ||
            !(iface.flags() & QNetworkInterface::CanMulticast)) {
            continue;
        }

        // 根据IP地址段筛选
        QList<QNetworkAddressEntry> entries = iface.addressEntries();
        foreach (const QNetworkAddressEntry& entry, entries) {
            if (entry.ip().protocol() == QAbstractSocket::IPv4Protocol &&
                entry.ip().toString().startsWith(ip)) {
                targetInterface = iface;
                break;
            }
        }
        if (targetInterface.isValid()) break;
    }

    if (!targetInterface.isValid()) {
        qDebug() << "netip=" << targetInterface.name();
        qDebug() << "未找到可用的组播网卡";
        return QNetworkInterface();
    }
    return targetInterface;
}
